package game.grounds;

import edu.monash.fit2099.engine.positions.Ground;
import edu.monash.fit2099.engine.positions.Location;
import game.items.Food;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/** 抽象树：每隔固定回合在周围（半径=1）掉落一个果实。 */
public abstract class Tree extends Ground {

    private final int period;
    private int counter = 0;

    public Tree(char displayChar, int period) {
        super(displayChar, "树");
        this.period = period;
    }

    /** 返回要掉落的果实（由子类决定）。 */
    public abstract Food createFruit();

    @Override
    public void tick(Location location) {
        super.tick(location);
        counter++;
        if (counter % period == 0) {
            dropFruitNearby(location);
        }
    }

    /** 在半径=1 的随机邻近格（若没有则落在本格）掉落一个果实。 */
    protected void dropFruitNearby(Location location) {
        Food fruit = createFruit();
        List<Location> nearby = location.getNearbyLocations(1);
        Location target = nearby.isEmpty()
                ? location
                : nearby.get(ThreadLocalRandom.current().nextInt(nearby.size()));
        target.addItem(fruit);
    }
}
